import HotkeyRegister from './HotkeyRegister'
import { HotkeyType } from './useHotkey'
import { Keys } from './types'
import { isElEditable } from '@/utils'
import { getWidgetSelection } from './utils'

/** 控件操作 */
export default function useWidgetOperate(register: HotkeyRegister) {
  /**
   * 删除控件或子选项
   */
  register.add({
    keys: [Keys.Delete, Keys.Backspace],
    type: HotkeyType.KEYUP,
    handler: ({ e, viewer }) => {
      if (isElEditable(e.target)) return

      const list = getWidgetSelection(viewer).filter(widget => widget.removable)

      if (!list.length) return

      // 选择单个时，单复选框存在多个选项时，删除当前选项
      if (list.length === 1) {
        const { checkOptions, activeOption } = list[0]

        if (activeOption && checkOptions.length > 1) {
          checkOptions.splice(checkOptions.indexOf(activeOption), 1)
          return
        }
      }

      viewer.removeWidgets(list, false, true)
    }
  })
}
